package asia.doing.service.user;

import asia.doing.common.enums.LikesModuleEnum;
import asia.doing.common.enums.RoleEnum;
import asia.doing.common.utils.TokenUtils;
import asia.doing.common.utils.UUIDUtils;
import asia.doing.entity.*;
import asia.doing.mapper.BlogMapper;
import asia.doing.service.admin.ManageUserService;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 博客信息业务处理
 **/
@Service(value = "frontBlogService")
public class FrontBlogService {

    @Resource
    private BlogMapper blogMapper;

    @Resource
    private FrontLikesService frontLikesService;

    @Resource
    private ManageUserService manageUserService;

    @Resource
    private FrontCollectService frontCollectService;

    /**
     * 新增
     */
    public void add(Blog blog) {
        // 使用uuid作为唯一性的id进行插入数据
        blog.setId(UUIDUtils.getUUIDInOrderId());
        blogMapper.insert(blog);
    }

    /**
     * 删除
     */
    public void deleteById(Long id) {
        blogMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Long> ids) {
        for (Long id : ids) {
            blogMapper.deleteById(id);
        }
    }


    /**
     * 修改
     */
    public void updateById(Blog blog) {
        blogMapper.updateById(blog);
    }

    /**
     * 根据ID查询
     */
    public Blog selectById(Long id) {
        Blog blog = blogMapper.selectById(id);
//        查询当前用户总共的文章数量
        User user = manageUserService.selectById(blog.getUserId());
        List<Blog> userBlogList = blogMapper.selectUserBlog(user.getId());
        System.out.println("博客的数量总共为:" + userBlogList.size());
        user.setBlogCount(userBlogList.size());
        System.out.println("用户信息为" + user.toString());
        //查询当前用户收到的点赞和收藏数据
        int userLikesCount = 0;
        int userCollectCount = 0;
        for (Blog blog1 : userBlogList) {
            Long fid = blog1.getId();
            int likesCount = frontLikesService.selectByFidAndModule(fid, LikesModuleEnum.BLOG.getValue());
            userLikesCount += likesCount;

            int collectCount = frontCollectService.selectByFidAndModule(fid, LikesModuleEnum.BLOG.getValue());
            userCollectCount += collectCount;
        }
        user.setLikesCount(userLikesCount);
        user.setCollectCount(userCollectCount);

        //将更新后的user对象传入到blog对象之后
        blog.setUser(user);

        // 查询当前博客的点赞数据
        int likesCount = frontLikesService.selectByFidAndModule(id, LikesModuleEnum.BLOG.getValue());
        blog.setLikesCount(likesCount);
        Likes userLikes = frontLikesService.selectUserLikes(id, LikesModuleEnum.BLOG.getValue());
        blog.setUserLike(userLikes != null);

        // 查询当前博客的收藏数据
        int collectCount = frontCollectService.selectByFidAndModule(id, LikesModuleEnum.BLOG.getValue());
        blog.setCollectCount(collectCount);
        Collect userCollect = frontCollectService.selectUserCollect(id, LikesModuleEnum.BLOG.getValue());
        blog.setUserCollect(userCollect != null);

        System.out.println("博客的详细信息" + blog.toString());

        //浏览次数+1
        blog.setReadCount(blog.getReadCount() + 1);
        this.updateById(blog);

        //返blog信息
        return blog;
    }

    /**
     * 查询所有
     */
    public List<Blog> selectAll(Blog blog) {
        return blogMapper.selectAll(blog);
    }

    /**
     * 分页查询
     */
    public PageInfo<Blog> selectPage(Blog blog, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Blog> list = blogMapper.selectAll(blog);
        return PageInfo.of(list);
    }

    /**
     * 分页查询
     * @return
     */
    public List<Blog> selectTop(){
        List<Blog> blogList = this.selectAll(null);
        blogList = blogList.stream().sorted((b1, b2) -> b2.getReadCount().compareTo(b1.getReadCount()))
                .limit(20)
                .collect(Collectors.toList());
        return blogList;
    }


    /**
     * 博客推荐
     */
    public Set<Blog> selectRecommend(Long blogId) {
        //首先根据文章id查询出对应的文章内容
        Blog blog = this.selectById(blogId);
        String tags = blog.getTags();
        Set<Blog> blogSet = new HashSet<>();
        //如果标签不为空的情况之下
        if(ObjectUtil.isNotEmpty(tags)){
            List<Blog> blogList = this.selectAll(null);
            JSONArray tagStr = JSONUtil.parseArray(tags);
            for (Object tag : tagStr) {
                //筛选出包含当前博客标签的其他的博客列表
                Set<Blog> collect = blogList.stream().filter(b -> b.getTags().contains(tag.toString()))
                        .collect(Collectors.toSet());
                blogSet.addAll(collect);
            }
        }
        //点赞和爱心后续添加内容
        blogSet.forEach(b -> {
                    int likesCount = frontLikesService.selectByFidAndModule(b.getId(), LikesModuleEnum.BLOG.getValue());
                b.setLikesCount(likesCount);
        });
        return blogSet.stream().limit(5).collect(Collectors.toSet());
    }

    // 查询用户点赞的数据
    public PageInfo<Blog> selectLike(Blog blog, Integer pageNum, Integer pageSize) {
        Account currentUser = TokenUtils.getCurrentUser();
        if (RoleEnum.USER.name().equals(currentUser.getRole())) {
            blog.setUserId(currentUser.getId());
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Blog> list = blogMapper.selectLike(blog);
        PageInfo<Blog> pageInfo = PageInfo.of(list);
        List<Blog> blogList = pageInfo.getList();
        for (Blog b : blogList) {
            int likesCount = frontLikesService.selectByFidAndModule(b.getId(), LikesModuleEnum.BLOG.getValue());
            b.setLikesCount(likesCount);
        }
        return pageInfo;
    }


    /* 个人用户界面开始 */

    public PageInfo<Blog> selectByUserId(Blog blog, Integer pageNum, Integer pageSize) {
        Account currentUser = TokenUtils.getCurrentUser();
        if (RoleEnum.USER.name().equals(currentUser.getRole())) {
            blog.setUserId(currentUser.getId());
        }
        //但是如果是管理员用户的时候，这个时候就默认筛选出首页的哪些数据
        PageHelper.startPage(pageNum, pageSize);
        List<Blog> list = blogMapper.selectAll(blog);
        PageInfo<Blog> pageInfo = PageInfo.of(list);
        return pageInfo;
    }

    public PageInfo<Blog> selectCollect(Blog blog, Integer pageNum, Integer pageSize) {
        Account currentUser = TokenUtils.getCurrentUser();
        if (RoleEnum.USER.name().equals(currentUser.getRole())) {
            blog.setUserId(currentUser.getId());
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Blog> list = blogMapper.selectCollect(blog);
        PageInfo<Blog> pageInfo = PageInfo.of(list);
        List<Blog> blogList = pageInfo.getList();
        for (Blog b : blogList) {
            int likesCount = frontLikesService.selectByFidAndModule(b.getId(), LikesModuleEnum.BLOG.getValue());
            b.setLikesCount(likesCount);
        }
        return pageInfo;
    }

    public PageInfo<Blog> selectComment(Blog blog, Integer pageNum, Integer pageSize) {
        Account currentUser = TokenUtils.getCurrentUser();
        if (RoleEnum.USER.name().equals(currentUser.getRole())) {
            blog.setUserId(currentUser.getId());
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Blog> list = blogMapper.selectComment(blog);
        PageInfo<Blog> pageInfo = PageInfo.of(list);
        List<Blog> blogList = pageInfo.getList();
        for (Blog b : blogList) {
            int likesCount = frontLikesService.selectByFidAndModule(b.getId(), LikesModuleEnum.BLOG.getValue());
            b.setLikesCount(likesCount);
        }
        return pageInfo;
    }

}